import React, { useState } from 'react'
import { Menu } from 'antd'
import { ROUTES_LIST } from '../../router/routes'
import { useLocation, useNavigate } from 'react-router-dom'
import { RouterRawState } from '../../types'
import { ItemType, MenuItemType } from 'antd/es/menu/hooks/useItems'
import { l } from '../../utils/storage'

const renderMenusItem = (
  routes: RouterRawState[]
): ItemType<MenuItemType>[] => {
  return (
    routes
      .filter((v) => {
        // 根据 hidden 筛选
        if (v.meta.hidden) return false
        return true
      })
      // 过滤选贤
      .filter((v) => {
        const userInfo = l.getItem('userInfo')
        const role = userInfo ? userInfo.role : 'unkown'
        // 优先判断管理员
        if (role === 'admin') return true
        // 是否需要权限
        else if (!v.meta.roles) {
          return true
        } else {
          // 不是管理员   并且需要权限
          return v.meta.roles.includes(role)
        }
      })
      .map((v) => {
        return {
          key: v.path,
          label: v.meta.title,
          icon: v.meta.icon,
          children: v.children && renderMenusItem(v.children),
        }
      })
  )
}

// const flatRouterList = (routes: RouterRawState[]) => {
//   return routes.reduce((p, n): RouterRawState[] => {
//     return n.children ? p.concat(flatRouterList(n.children)) : p.concat(n)
//   }, [] as RouterRawState[])
// }

export const SiderMenu: React.FC = () => {
  // 导航菜单列表
  const items = renderMenusItem(ROUTES_LIST)
  // 访问路径
  const { pathname } = useLocation()
  // 路由跳转
  const navigate = useNavigate()
  // 算法
  const [openKeys, setOpenKeys] = useState<string[]>(
    l.getItem('openKeys') || []
  )
  return (
    <div>
      <Menu
        mode="inline"
        onClick={({ key }) => navigate(key)}
        onOpenChange={(openKeys) => {
          l.setItem('openKeys', openKeys)
          setOpenKeys(openKeys)
        }}
        items={items}
        theme="dark"
        selectedKeys={[pathname]}
        openKeys={openKeys}
      ></Menu>
    </div>
  )
}
